﻿using Microsoft.Practices.ObjectBuilder2;

namespace UniAspect.UnityCommon.ResolutionLogging
{
    public class ResolutionLoggingStrategy : BuilderStrategy
    {
        public override void PreBuildUp(IBuilderContext context)
        {
            //context.Locator.
            var logger = context.Policies.Get<IResolutionLoggerPolicy>(context.OriginalBuildKey);
            if (logger != null)
            {
                ILoggingDepthPolicy currentDepth = GetLoggingDepthPolicy(context);
                logger.LogResolutionStarted(currentDepth.Depth, context.OriginalBuildKey);
                currentDepth.Increment();
            }
        }

        public override void PostBuildUp(IBuilderContext context)
        {
            var logger = context.Policies.Get<IResolutionLoggerPolicy>(context.OriginalBuildKey);
            if (logger != null)
            {
                ILoggingDepthPolicy currentDepth = GetLoggingDepthPolicy(context);
                currentDepth.Decrement();
                logger.LogResolutionCompleted(currentDepth.Depth, context.OriginalBuildKey, context.BuildKey,
                                              context.Existing);
            }
        }

        private ILoggingDepthPolicy GetLoggingDepthPolicy(IBuilderContext context)
        {
            var policy = context.Policies.Get<ILoggingDepthPolicy>(context.OriginalBuildKey);
            if (policy == null)
            {
                policy = new LoggingDepthPolicy();
                context.Policies.SetDefault(policy);
            }
            return policy;
        }
    }
}